package com.sharemarking.system.controller;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.util.*;

import com.aliyun.oss.model.ObjectMetadata;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.model.PutObjectRequest;
import com.sharemarking.system.service.ImageService;
import com.sharemarking.system.properties.CosProperties;
import com.tencent.cloud.CosStsClient;
import org.apache.commons.io.FileUtils;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import com.aliyun.oss.HttpMethod;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.GeneratePresignedUrlRequest;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;
import com.sharemarking.system.dto.OSSSign;
import com.sharemarking.system.dto.UserDetailImpl;
//import com.sharemarking.system.properties.AliOSSProperties;
//import com.sharemarking.system.properties.AliSecretProperties;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Controller
@RequestMapping("system/image")
public class ImageController {
	
//	@Autowired
//	AliSecretProperties sProp;
//
//	@Autowired
//	AliOSSProperties prop;
//
//	@Autowired
//	OSSClient client;

	@Autowired
	private ImageService imageService;

	@Autowired
	private CosProperties cop;

	@Autowired
	COSClient cosClient;


//	@GetMapping("upload")
//	public void upload(Model model) throws UnsupportedEncodingException{
//        model.addAttribute("host", client.getEndpoint().toString());
//	}
//	/**
//	 * @return
//	 * @throws UnsupportedEncodingException
//	 */
//	@GetMapping("sign")
//	@ResponseBody
//	public OSSSign sign(Authentication auth) throws UnsupportedEncodingException{
//		UserDetailImpl udi=(UserDetailImpl)auth.getPrincipal();
//    		long expireEndTime = System.currentTimeMillis() + 300000;
//        Date expiration = new Date(expireEndTime);
//        PolicyConditions policyConds = new PolicyConditions();
//        policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, 1048576000);
//        policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, udi.getId().toString());
//        String postPolicy = client.generatePostPolicy(expiration, policyConds);
//        byte[] binaryData = postPolicy.getBytes("utf-8");
//        String encodedPolicy = BinaryUtil.toBase64String(binaryData);
//        String postSignature = client.calculatePostSignature(postPolicy);
//        OSSSign sign=new OSSSign();
//        sign.setDir(udi.getId().toString());
//        sign.setAccessKeyId(sProp.getAccessKeyId());
//        sign.setPolicy(encodedPolicy);
//        sign.setSignature(postSignature);
//        return sign;
//	}
//
//	@GetMapping("get")
//	public String get(String key,String style){
//		long expireEndTime = System.currentTimeMillis() + 300000;
//        GeneratePresignedUrlRequest req = new GeneratePresignedUrlRequest(prop.getBucket(), key, HttpMethod.GET);
//        req.setExpiration(new Date(expireEndTime));
//        if(style!=null)req.setProcess(style);
//        URL url=client.generatePresignedUrl(req);
//		return "redirect:"+url.toString();
//	}


	/**
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	@GetMapping("sign")
	@ResponseBody
	public String cosSign() throws Exception{
		TreeMap<String, Object> config = new TreeMap<String, Object>();

		try {
			// 替换为您的 SecretId
			config.put("SecretId", cop.getSecretid());
			// 替换为您的 SecretKey
			config.put("SecretKey", cop.getSecretkey());

			// 临时密钥有效时长，单位是秒，默认1800秒，最长可设定有效期为7200秒
			config.put("durationSeconds", 1800);

			// 换成您的 bucket
			config.put("bucket", cop.getBucket());
			// 换成 bucket 所在地区
			config.put("region", cop.getRegion());

			// 这里改成允许的路径前缀，可以根据自己网站的用户登录态判断允许上传的具体路径，例子：a.jpg 或者 a/* 或者 * 。
			// 如果填写了“*”，将允许用户访问所有资源；除非业务需要，否则请按照最小权限原则授予用户相应的访问权限范围。
			config.put("allowPrefix", "*");

			// 密钥的权限列表。简单上传、表单上传和分片上传需要以下的权限，其他权限列表请看 https://cloud.tencent.com/document/product/436/31923
			String[] allowActions = new String[] {
					// 简单上传
					"name/cos:PutObject",
					// 表单上传、小程序上传
					"name/cos:PostObject",
					// 分片上传
					"name/cos:InitiateMultipartUpload",
					"name/cos:ListMultipartUploads",
					"name/cos:ListParts",
					"name/cos:UploadPart",
					"name/cos:CompleteMultipartUpload"
			};
			config.put("allowActions", allowActions);

			JSONObject credential = CosStsClient.getCredential(config);
			//成功返回临时密钥信息，如下打印密钥信息
			System.out.println(credential);
			return credential.toString();
		} catch (Exception e) {
			//失败抛出异常
			throw new IllegalArgumentException("no valid secret !");
		}
	}

	@GetMapping("get")
	public void cosGet(String key, HttpServletResponse response) throws Exception{
		Date expiration = new Date(System.currentTimeMillis() + 5 * 60 * 10000);
		URL url = cosClient.generatePresignedUrl(cop.getBucket(), key, expiration);
		response.sendRedirect(url.toString());
	}

	/**
	 *
	 * @param file
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="uploadBannerImage",method= RequestMethod.POST)
	@ResponseBody
	public Map<String,Object> uploadBannerImage(MultipartFile file, HttpServletRequest request)throws Exception{
		String type = request.getParameter("type");
		Map<String,Object> map = new HashMap<>();
		String name = file.getOriginalFilename();
		int namePrev  = name.lastIndexOf(".");
		String beforeName = type+"/"+System.currentTimeMillis()+"";
		String afterName = name.substring(namePrev);
		String fileName = beforeName+afterName;
		try {
			// 指定要上传到的存储桶
			String bucketName = cop.getBucket();
			// 指定要上传到 COS 上对象键
			File file1 = new File(name);
			FileUtils.copyInputStreamToFile(file.getInputStream(), file1);
			// 会在本地产生临时文件，用完后需要删除
			PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, fileName,file1);
			cosClient.putObject(putObjectRequest);
			if (file1.exists()) {
				file1.delete();
			}
		}catch (Exception e) {
			e.printStackTrace();
		}
		if(type.equals("editer")) {
			List<String > data=new ArrayList<>();
			data.add(imageService.getImageBasePath()+fileName);
			map.put("errno", 0);
			map.put("data", data);
			return map;
		}
		map.put("fileName",fileName);
		return map;
	}



//	@GetMapping("get")
//	public String get(String key){
//		Date expiration = new Date(System.currentTimeMillis() + 5 * 60 * 10000);
//		URL url = client.generatePresignedUrl(cop.getBucket(), key, expiration);
//		return "redirect:"+url.toString();
//	}




//	/**
//	 * 上传轮播图片
//	 * @param file
//	 * @param md5
//	 * @throws IOException
//	 */
//	@RequestMapping(value="uploadBannerImage",method= RequestMethod.POST)
//	@ResponseBody
//	public Map<String,Object> uploadBannerImage(MultipartFile file, HttpServletRequest request)throws Exception{
//		String type = request.getParameter("type");
//		Map<String,Object> map = new HashMap<>();
//		String name = file.getOriginalFilename();
//		int namePrev  = name.lastIndexOf(".");
//		String beforeName = type+"/"+System.currentTimeMillis()+"";
//		String afterName = name.substring(namePrev);
//		String fileName = beforeName+afterName;
//		try {
//			//设置上传公开读
//			ObjectMetadata objectMetadata = new ObjectMetadata();
//			objectMetadata.setHeader("x-oss-object-acl","public-read");
//			System.out.println(prop.getBucket());
//			client.putObject(prop.getBucket(),fileName,file.getInputStream(),objectMetadata);
//		}catch (Exception e) {
//			e.printStackTrace();
//		}
//		if(type.equals("editer")) {
//			List<String > data=new ArrayList<>();
//			data.add(imageService.getImageBasePath()+fileName);
//			map.put("errno", 0);
//			map.put("data", data);
//			return map;
//		}
//		map.put("fileName",fileName);
//		return map;
//	}
//
//	/**
//	 * 上传文件弹出框
//	 * @param
//	 * @return
//	 */
//	@RequestMapping(value="showFilePage/{type}/{image}",method= RequestMethod.GET)
//	public String showFilePage(@PathVariable("image")String image, @PathVariable("type")String type, Model model){
//		model.addAttribute("imageBasePath",imageService.getImageBasePath());
//		model.addAttribute("imageName",image);
//		model.addAttribute("imageType",type);
//		return "system/image/fileForm";
//	}
}
